define(["app",
        "md5",
        "services/MessageBox",
        "directives/common/OrgUserPicker",
        "controllers/user/OrgTreeController",
         "services/TipsService",
        "resources/UserExResource"
],  function(app) {
	
	 var deps = ["$scope","$modalInstance","$modal","selectedOrg", "selectedUser","UserExResource","TipsService"];
	 
	 function userDetailController($scope, $modalInstance,$modal,selectedOrg, selectedUser,UserExResource,TipsService) {
		//初始化
		$scope.selectedOrg = angular.copy(selectedOrg); // 传入选中的组织
		$scope.selectedOrgName = selectedOrg.orgName; // 传入选中的组织
		$scope.windowModel = selectedUser || {}; // 页面表单对象
		//var userNameBeforeEdit = angular.copy(selectedUser.userName); // 如果是编辑，修改前的用户名
		//var loginNameBeforeEdit = angular.copy(selectedUser.loginName); // 如果是编辑，修改前的登录名
		$scope.newOrgName=[];            //新设定的组织
		$scope.isEdit = false; // 判断是新增还是编辑
		var orgIndex=-1;   //编辑画面当前操作的第几个组织
		
		if (!selectedUser.userId) {
			$scope.sexText = "男"; // 性别选择，默认男
			$scope.windowModel.sex = 0;
			$scope.isEdit = false; 
		} else {
			$scope.isEdit = true;
		}

        $scope.windowModel.userOrg = [];

         //此处的$scope.windowModel.orgList是用户所属的组织
        if($scope.windowModel.orgList && $scope.windowModel.orgList.length>0){
            for(var i in $scope.windowModel.orgList){
                var org = $scope.windowModel.orgList[i];
                $scope.windowModel.userOrg.push({orgId:org.orgId, post:org.postName,orgType:org.orgType});
            }
        }

		//将模型中数据复制到临时变量
		$scope.syncNewOrgName = function() {
			var mainLen=$scope.windowModel.userOrg.length;
			for (var i=0;i<mainLen;i++){
				$scope.newOrgName.push(null);
				$scope.newOrgName[i]=angular.copy($scope.windowModel.userOrg[i]);
				//根据ID填上名称
				$scope.newOrgName[i].orgName=$scope.windowModel.orgList[i].orgName;
			}
		};

		//从临时变量复制组织ID到模型
		$scope.copyOrgId2Model = function() {			
			var iLen=$scope.windowModel.userOrg.length;			
			if(iLen>0){				
				for (var i=0;i<iLen;i++){
					$scope.windowModel.userOrg[i].orgId=$scope.newOrgName[i].orgId;
				}
			}
		};
		//提交前，删除空组织
		$scope.removeEmptyOrg = function() {			
			var iLen=$scope.windowModel.userOrg.length;			
			if(iLen>0){				
				for(var i=iLen-1;i>=0;i--){
				  if($scope.windowModel.userOrg[i].orgId==""){
					  $scope.windowModel.userOrg.splice(i,1);
				  }
				}
			}
		};		
		
		$scope.userOrgs = $scope.windowModel.userOrg; //引用，这两个变量旨向同一对象
		$scope.syncNewOrgName(); //同步		
			
		// 展开/收起组织节点
		$scope.openTree = function(org) {
			// 隐藏下级组织
			if (org.isSubsShow) {
				org.isSubsShow = false;
			} else {
				org.isSubsShow = true;
			}			
		};

        $scope.selectedOrg = $scope.selectedOrg || {};

        //如果是新增用户且当前有选中某组织，则打开新增用户编辑框时默认有选中的组织
        if($scope.selectedOrg.orgId && !$scope.isEdit){
            var newUserOrg = {};
            newUserOrg.orgId = $scope.selectedOrg.orgId;
            newUserOrg.post = $scope.selectedOrg.post;
            newUserOrg.orgName = $scope.selectedOrg.orgName;
            newUserOrg.orgType = $scope.selectedOrg.orgType;
            $scope.newOrgName.push(newUserOrg);
            $scope.userOrgs.push({
                orgId:newUserOrg.orgId,
                post:newUserOrg.post,
                orgType:newUserOrg.orgType
            });
        }

         //增加一行 组织+岗位
        $scope.addOrg= function() {
            $scope.userOrgs.push({orgId:"", post:""});
            $scope.newOrgName.push({orgId:"", post:"",orgName:""});
        };

		// 记录选择的组织
		$scope.record = function(org){			
			$scope.newOrgName[orgIndex]=org;		
			$scope.userOrgs[orgIndex].orgType=org.orgType;

			//alert(JSON.stringify($scope.newOrgName));
		};

        $scope.getSelectedOrg = function(orgList,index){
            if(orgList && orgList.length>0){
                $scope.saveIndexOrg(index);
                $scope.record(orgList[0]);
            }
        };
		//保存用户修改画面中，选中第几个组织
		$scope.saveIndexOrg= function(ival){	
			orgIndex=ival;			
		};

		//点击保存
		$scope.submit = function() {
			if (!$scope.windowModel.loginName) {
                alert('登录用户是必填项');
				return;
			}
			if (!$scope.windowModel.userName) {
				alert('姓名是必填项');
				return;
			}		
			if(!$scope.userOrgs || $scope.userOrgs.length == 0 ){
				alert('请选择用户所属组织');
				return;
			}

			$scope.copyOrgId2Model();//将临时变量的值复制到提交模型中

            for(var i=0;i<$scope.userOrgs.length;i++){
                if(!$scope.userOrgs[i].orgId){
                    alert('请选择用户所属组织');
                    return;
                }
                if(!$scope.userOrgs[i].post){
                    alert('请填写用户所在组织的岗位');
                    return;
                }
            }

			$scope.removeEmptyOrg(); //删除数组中空的组织
			//$scope.windowModel.isStop = false;			
			$scope.windowModel.password = hex_md5("1a2b3c4d"); // 默认密码
			
			if (!$scope.isEdit) {				
				UserExResource.checkUserForm($scope.windowModel.loginName,$scope.windowModel.userName).success(function(resp){	
					//alert(JSON.stringify(resp));
					if (resp.CODE=="OK") {
                        var user = {};
                        user.loginName = $scope.windowModel.loginName;
                        user.sex = $scope.windowModel.sex;
                        user.userOrg = $scope.windowModel.userOrg;
                        user.userName = $scope.windowModel.userName;
                        user.userId = $scope.windowModel.userId;
                        user.password = $scope.windowModel.password;
						$scope.saveUser(user);
					}else{
						alert(resp.MSG);//"已经存在的用户名"); //判断登录名是否已经存在
						return;
					}
				});				
				
			} else {
							
				//判断用户名是否已经存在
				UserExResource.checkUserForUpdate($scope.windowModel.loginName,$scope.windowModel.userName, $scope.windowModel.userId ).success(function(resp){
					if (resp.CODE=="OK") {
                        var user = {};
                        user.loginName = $scope.windowModel.loginName;
                        user.sex = $scope.windowModel.sex;
                        user.userOrg = $scope.windowModel.userOrg;
                        user.userName = $scope.windowModel.userName;
                        user.userId = $scope.windowModel.userId;
						$scope.updateUser(user);
					}else {							
						alert(resp.MSG);//"已经存在的用户名");
						return;
					}
				});				
				
			}
			//刷新list画面
		}

		// 取消
		$scope.cancel = function() {
			$modalInstance.dismiss('no');
		};
		
		// 清空指定
		$scope.cancelOrg = function(index) {
//			$scope.userOrgs[index].orgId="";
//			$scope.userOrgs[index].post="";
//			$scope.newOrgName[index].orgName="";
//			$scope.newOrgName[index].orgId="";
//			$scope.newOrgName[index].post="";
            $scope.userOrgs.splice(index,1);
            $scope.newOrgName.splice(index,1);
		};
		
		// 选择性别
		$scope.setSex = function (sex) {
			if (0==sex) {
				$scope.sexText = "男";
				$scope.windowModel.sex = 0;
			} else if (1==sex) {
				$scope.sexText = "女";
				$scope.windowModel.sex = 1;
			}
		};

		$scope.setSex(selectedUser.sex);
		
		// 保存用户
		$scope.saveUser = function(user) {	
			UserExResource.saveUser(user).success(function(resp) {
				// 关闭窗口并传递参数
				$modalInstance.close(resp);

                TipsService.show('新增用户成功! 初始密码：1a2b3c4d');
			});
			
		}
		// 更新用户信息
		$scope.updateUser = function(user) {			
			UserExResource.updateUser(user).success(function(resp) {
				// 关闭窗口并传递参数
				$modalInstance.close(resp);

                TipsService.show('用户更改成功!');
			});
			
		}
	 }	//end userController
		
		
	
	
	userDetailController.$inject = deps;
    return app.lazy.controller("UserDetailController", userDetailController);
});
